// pages/music/detail.js
import props from '../../utils/js/props.js'
import common from '../../utils/js/common.js'
import ajax from '../../utils/js/ajax.js'
const app = getApp()
let audioDom = app.audioDom;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navTitle: '',
    player:{},
    id: '',
    audioDom:'',
    animation: null,
    ismask:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('onLoad')
    let id = options.id || 1
    if (id == app.player.playing.id){
      this.setData({ id }, ()=>{
        this.updateLrc()
      })
    }else{
      wx.stopBackgroundAudio()
      this.setData({ id: options.id || 1 }, () => {
        this.getDetail()
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    props.setPlayer.call(this, app.player)
    this.audioWatch()
    this.maskAnima();   
    //动画完成后将遮罩层隐藏
    setTimeout(() => {
      this.setData({
        ismask:true,
      })    
    }, 2000);
  },
  //遮罩层动画
maskAnima(){
  var animation = wx.createAnimation({
    duration: 2000,
    timingFunction: 'ease-out',
  });
  animation.opacity(0).step()
  this.setData({
    animation:  animation.export()
  })
},
  updeData(current_music){
    if (current_music !== this.data.current_music) {
      props.setPlayer.call(this, { current_music })
      props.setPlaying.call(this, app.player.list[current_music], ()=>{
        this.playAudio()
        this.setData({ id: app.player.playing.id }, () => this.updateLrc())
      })
    }
  },
  getDetail() {
     // 测试数据
     let testData = {
      a_resource: "http://audio.22family.com/",
      i_resource: "http://audio.22family.com/",
      audio: {
        cover:'audio/cover/1553691847955147665',
        created:1553691849,
        id:4,
        // lrc:`[00:00.000] 作曲 : 姬霄
        // [00:01.000] 作词 : 花粥
        // [00:04.95]混音：卢润泽
        // [00:18.24]劫过九重城关 我座下马正酣
        // [00:23.21]看那轻飘飘的衣摆 趁擦肩把裙掀
        // [00:28.68]踏遍三江六岸 借刀光做船帆
        // [00:35.56]任露水浸透了短衫 大盗睥睨四野
        // [00:39.65]枕风宿雪多年 我与虎谋早餐
        // [00:50.17]拎着钓叟的鱼弦 问卧龙几两钱
        // [00:56.60]蜀中大雨连绵 关外横尸遍野
        // [01:01.93]你的笑像一条恶犬 撞乱了我心弦
        // [01:22.90]谈话饮月赋闲 这春宵艳阳天
        // [01:26.00]待到梦醒时分睁眼 铁甲寒意凛冽
        // [01:34.34]夙愿只隔一箭 故乡近似天边
        // [01:40.88]不知何人浅唱弄弦 我彷徨不可前
        // [01:55.48]枕风宿雪多年 我与虎谋早餐
        // [01:59.05]拎着钓叟的鱼弦 问卧龙几两钱
        // [02:03.18]蜀中大雨连绵 关外横尸遍野
        // [02:07.46]你的笑像一条恶犬 撞乱我心弦
        // [02:16.00]烽烟万里如衔 掷群雄下酒宴
        // [02:23.33]谢绝策勋十二转 想为你窃玉簪
        // [02:28.55]入巷间吃汤面 笑看窗边飞雪
        // [02:37.55]取腰间明珠弹山雀 立枇杷于庭前
        // [02:47.09]入巷间吃汤面 笑看窗边飞雪
        // [02:50.70]取腰间明珠弹山雀 立枇杷于庭前`,
        lrc:`[00:00]我的儿他表家乡那个泪珠滚[00:07]在校场可喜坏了那些忠良臣[00:13]宋主听此言欢喜不尽[00:20]他知道咱杨门辈辈是忠臣[00:26]刀劈王伦他也不怪[00:29]又把那个招讨帅印赐与了儿身[00:36]文广儿欢天喜地把府进[00:39]【垛子板】我一见帅印气在了心[00:42]我本想进京辞帅印[00:44]小女儿搬来了老太君[00:46]老太君为国把忠尽，她命我挂帅平反臣[00:49]一不为官，二不为宦[00:52]为的是那大宋江山和黎民[00:55]此一番到在两军阵[00:58]【紧二八】我不杀安王贼我不回家门！`,
        name:'盗将行',
        singer:{
          avatar:'singer/avatar/1553742725639053013',
          name:'花僮',
        },
        singer_id:"1026069",
        type:0,
        url:'audio/url/1553691846205912532'
      }
    }
    let { a_resource, i_resource } = testData;
    // let { lrc, id, url, cover, singer, name } = testData.audio
    let { wordFileUrl, excerptId, fileUrl, cover, singer, excerpt } = wx.getStorageSync('currentResource')
    let { timeArr,lrcArr } = common.analysis(wordFileUrl)
    // props.setPlaying.call(this, { id, timeArr, lrcArr, url, singer, name, cover })
    props.setPlaying.call(this, { id:excerptId, timeArr, lrcArr, url:fileUrl, singer, name:excerpt, cover })
    props.setPlayer.call(this, { i_resource, a_resource, global_show: 1, status: 0 })

    console.log(lrcArr,'lrcArr')
    this.playAudio()
    // ajax.get('audio/detail', { id: this.data.id }).then(res => {
    //   if (res.code === 0) {
    //     let { a_resource, i_resource } = res.data;
    //     let { lrc, id, url, cover, singer, name } = res.data.audio
    //     let { timeArr, lrcArr } = common.analysis(lrc)
    //     props.setPlaying.call(this, { id, timeArr, lrcArr, url, singer, name, cover })
    //     props.setPlayer.call(this, { i_resource, a_resource, global_show: 1, status: 1 })

    //     this.playAudio()
    //   }
    // })
  },
  updateLrc() {
    ajax.get('lrc', { id: this.data.id }).then(res => {
      if (res.code === 0) {
        let lrc = res.data.lrc
        let { timeArr, lrcArr } = common.analysis(lrc)
        props.setPlaying.call(this, { timeArr, lrcArr })
      }
    })
  },
  audioWatch(){
    let audioDom = app.audioDom
    audioDom.onPlay(() => {
      props.setPlayer.call(this, { status: 1 })
      props.setPlaying.call(this, { duration: audioDom })
    })
    audioDom.onPause(()=>{
      props.setPlayer.call(this, { status: 2 })
    })
    audioDom.onTimeUpdate(() => {
      props.setPlaying.call(this, { currentTime: audioDom.currentTime })
    })
    audioDom.onEnded(() => {
      // 安卓监听不到。。。，并没有问题，是将接口使用错误了
      // wx.showModal({
      //   title: '我是标题', //提示的标题
      //   content: '我是内容', //提示的内容
      //   success: function(res) {
      //     if(res.confirm) {
      //       console.log('用户点击了确定')
      //     } else if (res.cancel) {
      //       console.log('用户点击了取消')
      //     }
      //   }
      // })
      this.audioEnded()
    })
  },
  audioEnded(){
    let player = app.player, playing = app.player.playing;
    let mode = app.player.mode;
    switch (mode) {  // 0 单曲    1 顺序   2 随机
      case 0:
        console.log('单曲模式')
        this.playAudio()
        break;
      case 1:
        if (player.list.length > 0) {
          console.log('列表模式下一曲')
          let current_music = player.current_music + 1
          if (current_music >= player.list.length) {
            current_music = 0;
          }
          this.updeData(current_music)
          return
        }
        app.audioDom.pause()
        break;
      case 2:
        if (player.list.length > 0) {
          console.log('随机模式下一曲')
          let current_music = Math.floor(Math.random() * player.list.length)
          this.updeData(current_music)
          return
        }
        app.audioDom.pause()
        break;
      default:
        app.audioDom.pause()
    }
  },
  playAudio(){
    let audioDom = app.audioDom
    wx.setNavigationBarTitle({
      title: app.player.playing.name
    })
    this.setData({
      navTitle: app.player.playing.name
    })
    audioDom.title = app.player.playing.name
    // audioDom.src = app.player.a_resource + app.player.playing.url
    // audioDom.src = `https://ex-sycdn.kuwo.cn/218533479939989985f004f45fc8d784/6627ec5b/resource/n2/77/50/3917248439.mp3`
    audioDom.src = wx.getStorageSync('currentResource').accUrl
    audioDom.coverImgUrl = app.player.i_resource + app.player.playing.cover + '-ph'
    console.log( audioDom.src )
    // audioDom.play()
    // let that = this
    // audioDom.duration = 198.321633
    // props.setPlaying.call(this, { duration:  198.321633})
    // audioDom.onCanplay(()=> {
    //   // 必须。可以当做是初始化时长
    //   audioDom.duration;
    //   // 必须。不然也获取不到时长
    //   setTimeout(() => {
    //     console.log(audioDom.duration); // 401.475918
    //   }, 1000)
    // })  
  },
  playLast() {
    let current_music = app.player.current_music - 1
    if (current_music < 0) {
      current_music = app.player.list.length - 1
    }
    props.setPlayer.call(this, { current_music })
    this.setData({ current_music }, () => {
      let id = app.player.list[current_music].id
      this.setData({ id }, () => this.getDetail())
    })
  },
  playNext() {
    let current_music = app.player.current_music + 1
    if (current_music >= app.player.list.length) {
      current_music = 0
    }
    props.setPlayer.call(this, { current_music })
    this.setData({ current_music }, () => {
      let id = app.player.list[current_music].id
      this.setData({ id }, () => this.getDetail())
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    app.audioDom.stop()
    app.player = {
      list: [],
      current_music: 0,
      mode: 0,            // 0 单曲    1 顺序   2 随机
      status: 0,          // 0 未播放  1 播放   2 暂停中  3 已结束
      playbackRate: 1,    // 倍速
      a_resource: '',
      i_resource: '',
      global_show: 0,     // 全局显示  0 不显示 1 显示
      playing: {
        id: '',
        name: '',
        cover: '',
        url: '',
        singer: {
          avatar: '',
          name: ''
        },
        currentTime: 0,
        duration: 0,
        timeArr: [],
        lrcArr: []
      }
    }
    console.log('onHide')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.audioDom.stop()
    app.player = {
      list: [],
      current_music: 0,
      mode: 0,            // 0 单曲    1 顺序   2 随机
      status: 0,          // 0 未播放  1 播放   2 暂停中  3 已结束
      playbackRate: 1,    // 倍速
      a_resource: '',
      i_resource: '',
      global_show: 0,     // 全局显示  0 不显示 1 显示
      playing: {
        id: '',
        name: '',
        cover: '',
        url: '',
        singer: {
          avatar: '',
          name: ''
        },
        currentTime: 0,
        duration: 0,
        timeArr: [],
        lrcArr: []
      }
    }
    console.log('onUnload')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})